<template>
  <div ref="containerRef" class="detail">
    <div class="detail_header">
      <a-affix :target="(containerRef as HTMLElement)">
        <a-page-header title="待办事项" :subtitle="title" @back="onBack">
          <template #extra>
            <a-space>
              <a-button type="secondary" @click="onBack">
                <template #icon>
                  <icon-close/>
                </template>
                <template #default>取消</template>
              </a-button>
              <a-button type="primary" @click="save(false)">
                <template #icon>
                  <icon-save v-if="isUpdate && form.status === 3"/>
                  <icon-send v-else/>
                </template>
                <template #default>{{ isUpdate && form.status === 3 ? '创建' : '提交' }}</template>
              </a-button>
            </a-space>
          </template>
        </a-page-header>
      </a-affix>
    </div>
    <div class="detail_content" style="display: flex; flex-direction: column;">
      <GiForm ref="formRef" v-model="form" :columns="columns">
        <template #todoUsers>
          <a-select
              v-model="form.todoUsers"
              :options="userList"
              multiple
              :max-tag-count="4"
              :allow-clear="true"
          />
          <a-tooltip content="选择用户">
            <a-button @click="onOpenSelectUser">
              <template #icon>
                <icon-plus/>
              </template>
            </a-button>
          </a-tooltip>
        </template>
        <template #todoMethods>
          <a-checkbox-group v-model="form.todoMethods" :options="todo_method_enum"/>
        </template>
      </GiForm>
    </div>

    <a-modal
        v-model:visible="visible"
        title="用户选择"
        :mask-closable="false"
        :esc-to-close="false"
        :width="width >= 1100 ? 1100 : '100%'"
        draggable
        @close="reset"
    >
      <UserSelect v-if="visible" ref="UserSelectRef" v-model:value="form.todoUsers" @select-user="onSelectUser"/>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {Message} from '@arco-design/web-vue'
import {useWindowSize} from '@vueuse/core'
import {addTodo, getTodo, updateTodo} from '@/apis/system/todo'
import {listUserDict} from '@/apis'
import {type ColumnItem, GiForm} from '@/components/GiForm'
import type {LabelValueState} from '@/types/global'
import {useTabsStore} from '@/stores'
import {useResetReactive} from '@/hooks'
import {useDict} from '@/hooks/app'

const {width} = useWindowSize()
const route = useRoute()
const router = useRouter()
const tabsStore = useTabsStore()

const {id, type} = route.query
const isUpdate = computed(() => type === 'update')
const title = computed(() => (isUpdate.value ? '修改' : '新增'))
const containerRef = ref<HTMLElement | null>()
const formRef = ref<InstanceType<typeof GiForm>>()
const {
  priority_type,
  todo_type,
  todo_status_enum,
  todo_business_enum,
  todo_scope_enum,
  todo_method_enum
} = useDict('priority_type', 'todo_type', 'todo_status_enum', 'todo_business_enum', 'todo_scope_enum', 'todo_method_enum')

const [form, resetForm] = useResetReactive({
  title: '',
  content: '',
  priority: '',
  type: '',
  todoScope: 1,
  todoMethods: [1],
  isRemind: false,
  remindTime: undefined,
  startTime: undefined,
  endTime: undefined,
  isTop: false,
  status: 1,
})

const columns: ColumnItem[] = reactive([
  {
    label: '标题',
    field: 'title',
    type: 'input',
    span: 24,
    props: {
      maxLength: 150,
      showWordLimit: true,
    },
    rules: [{required: true, message: '请输入标题'}],
  },
  {
    label: '通知方式',
    field: 'todoMethods',
    type: 'checkbox',
    disabled: () => {
      return form.status === 3
    },
  },
  {
    label: '优先级',
    field: 'priority',
    type: 'select',
    props: {
      options: priority_type,
    },
    rules: [{required: true, message: '请选择优先级'}],
  },

  {
    label: '类型',
    field: 'type',
    type: 'select',
    props: {
      options: todo_type,
    },
    rules: [{required: true, message: '请选择待办类型'}],
  },
  {
    label: '业务类型',
    field: 'businessType',
    type: 'select',
    hide: () => {
      return !['3'].includes(form.type)
    },
    props: {
      options: todo_business_enum,
    },
    rules: [{required: true, message: '请选择业务类型'}],
  },
  {
    label: '通知范围',
    field: 'todoScope',
    type: 'radio-group',
    hide: () => {
      return !['2'].includes(form.type)
    },
    disabled: () => {
      return form.status === 3
    },
    props: {
      options: todo_scope_enum,
    },
    rules: [{required: true, message: '请选择通知范围'}],
  },
  {
    label: '指定用户',
    field: 'todoUsers',
    type: 'select',
    hide: () => {
      return form.todoScope === 1
    },
    rules: [{required: true, message: '请选择指定用户'}],
  },
  // {
  //   label: '定时',
  //   field: 'isRemind',
  //   type: 'switch',
  //   disabled: () => {
  //     return form.status === 3
  //   },
  //   props: {
  //     type: 'round',
  //     checkedValue: true,
  //     uncheckedValue: false,
  //     checkedText: '是',
  //     uncheckedText: '否',
  //   },
  // },
  {
    label: '提醒时间',
    field: 'remindTime',
    type: 'date-picker',
    hide: () => {
      return !form.isRemind
    },
    required: true,
    props: {
      showTime: true,
      placeholder: '请选择发布时间',
      // defaultValue: new Date(), // 设置默认值为当前时间
    },
  },
  // {
  //   label: '开始时间',
  //   field: 'startTime',
  //   type: 'date-picker',
  //   hide: () => {
  //     return !form.isRemind
  //   },
  //   required: true,
  //   props: {
  //     showTime: true,
  //     placeholder: '请选择发布时间（起始）',
  //     defaultValue: new Date(), // 设置默认值为当前时间
  //   },
  // },
  {
    label: '截至时间',
    field: 'endTime',
    type: 'date-picker',
    hide: () => {
      return !form.isRemind
    },
    required: true,
    props: {
      showTime: true,
      placeholder: '请选择截至时间',
      // defaultValue: new Date(Date.now() + 24 * 60 * 60 * 1000), // 设置默认值为当前时间的后一天
    },
  },
  {
    label: '内容',
    field: 'content',
    type: 'textarea',
    span: 24,
    props: {
      maxLength: 150,
      showWordLimit: true,
    },
    rules: [{required: true, message: '请输入内容'}],
  },

  {
    label: '置顶',
    field: 'isTop',
    type: 'switch',
    props: {
      type: 'round',
      checkedValue: true,
      uncheckedValue: false,
      checkedText: '是',
      uncheckedText: '否',
    },
  },
])

// 修改
const onUpdate = async (id: string) => {
  resetForm()
  const res = await getTodo(id)
  Object.assign(form, res.data)
}

// 返回
const onBack = () => {
  router.back()
  tabsStore.closeCurrent(route.path)
}

// 保存
const save = async (isDraft: boolean) => {
  const isInvalid = await formRef.value?.formRef?.validate()
  if (isInvalid) return false
  try {
    // 通知范围 所有人 去除指定用户
    // 根据类型设置通知用户
    // 1.个人待办 - 无感的设置当前登录用户
    // 2.团队待办 - 就是设置的通知用户
    // 3.申请待办 - 设置当前用户的上级（特定的角色）
    // 1和3的处理放到后端处理 - 添加前预处理
    form.todoUsers = (form.type === '1' || form.type === '3') ? null : form.todoUsers
    form.status = isDraft ? 1 : 2
    if (isUpdate.value) {
      await updateTodo(form, id as string)
      Message.success('修改成功')
    } else {
      await addTodo(form)
      Message.success('新增成功')
    }
    onBack()
    return true
  } catch (error) {
    console.error(error)
    return false
  }
}

// 打开用户选择窗口
const visible = ref(false)
const onOpenSelectUser = () => {
  visible.value = true
}

const UserSelectRef = ref()
// 重置
const reset = () => {
  UserSelectRef.value?.onClearSelected()
}

// 用户选择回调
const onSelectUser = (value: string[]) => {
  form.todoUsers = value
  formRef.value?.formRef?.validateField('todoUsers')
}

const userList = ref<LabelValueState[]>([])
onMounted(async () => {
  // 当id存在与type为update时，执行修改操作
  if (id && isUpdate.value) {
    await onUpdate(id as string)
  }
  // 获取所有用户
  const {data} = await listUserDict()
  userList.value = data.map((item) => ({...item, value: `${item.value}`}))
})
</script>

<style scoped lang="less"></style>
